//
//  UIImage+SWAdd.m
//  QZMJ
//
//  Created by 曾少伟 on 2016/12/5.
//  Copyright © 2016年 曾少伟. All rights reserved.
//

#import "UIImage+SWAdd.h"

#define kImgScale 1.33

@implementation UIImage (SWAdd)

+ (UIImage *)cutimageFromSourceName:(NSString *)sourceName andPlistImageName:(NSString *)imageName {
    return [self cutimageFromSourceName:sourceName andPlistImageName:imageName imgScale:1];
}

+ (UIImage *)cutimageFromSourceName:(NSString *)sourceName
             andPlistImageName:(NSString *)imageName
                      imgScale:(CGFloat)scale
{
    return [self cutimageFromSourceName:sourceName andPlistImageName:imageName imgScale:scale fitScale:FITW];
}
+ (UIImage *)cutimageFitScaleHFromSourceName:(NSString *)sourceName
                  andPlistImageName:(NSString *)imageName
                           imgScale:(CGFloat)scale
{
    return [self cutimageFromSourceName:sourceName andPlistImageName:imageName imgScale:scale fitScale:FITH];
}

+ (UIImage *)cutimageFromSourceName:(NSString *)sourceName
                  andPlistImageName:(NSString *)imageName
                           imgScale:(CGFloat)scale
                                fitScale:(CGFloat)fitScale
{
    UIImage *bundleImage = [UIImage imageNamed:imageName];
    if (bundleImage) {
        // 修改图片的尺寸
        bundleImage = [bundleImage imageWithNewScaledToSize:CGSizeMake(bundleImage.size.width  * scale * FITW, bundleImage.size.height * scale  * FITW)];
        return bundleImage; //如果bundle内有图片就直接返回；
    }
    
    //QzLoginRes QzLobRes
    UIImage *image = [UIImage imageNamed:sourceName];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:sourceName ofType:@"plist"];
    NSDictionary *imageDic = [NSDictionary dictionaryWithContentsOfFile:path];
    
    NSDictionary *metaDic = [imageDic objectForKey:@"metadata"];
    NSString *metaSizeStr = [metaDic objectForKey:@"size"];
    metaSizeStr = [metaSizeStr substringWithRange:NSMakeRange(1,metaSizeStr.length - 2)];
    NSString *sizeWStr = [metaSizeStr componentsSeparatedByString:@","][0];
    NSString *sizeHStr = [metaSizeStr componentsSeparatedByString:@","][1];
    if (sizeWStr.floatValue > sizeHStr.floatValue) {
        if ([sourceName isEqualToString:QZLOBRES]){
            image = [image imageByRotateRight90];
        }else{
            
        }
    }
    
    NSDictionary *frameDic = [imageDic objectForKey:@"frames"];
    //NSString *key = [imageName stringByAppendingString:@".png"];
    NSDictionary *imageInfoDic = [frameDic objectForKey:imageName];
    NSString *rectStr =  [imageInfoDic objectForKey:@"textureRect"];
    //NSLog(@"str`%@",rectStr);
    
    NSArray *arr = [rectStr componentsSeparatedByString:@","];
    
    NSString *leftStr = [arr[0] substringFromIndex:2];
    CGFloat left = leftStr.floatValue;
    
    NSString *topStr = [arr[1] substringToIndex:((NSString *)arr[1]).length - 1];
    CGFloat top = topStr.floatValue;
    
    NSString *widthStr = [arr[2] substringFromIndex:1];
    CGFloat width = widthStr.floatValue;
    
    NSString *heightStr = [arr[3] substringToIndex:((NSString *)arr[3]).length - 2];
    CGFloat height = heightStr.floatValue;
    
    
    CGImageRef sourceImageRef = image.CGImage;
    // 是否需要旋转
    BOOL rotate = [[imageInfoDic objectForKey:@"textureRotated"] boolValue];
    
    UIImage *newImage;
    
    if (rotate) {
        CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, CGRectMake(left, top, height,width));
        newImage = [UIImage imageWithCGImage:newImageRef];
        newImage = [newImage imageByRotateLeft90];
        
    }else{
        CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, CGRectMake(left, top, width, height));
        newImage = [UIImage imageWithCGImage:newImageRef];
    }
    
    if ([imageName isEqualToString:@"com_toast_bg.png"]||[imageName isEqualToString:@"com_dialog_bg.png"]||[imageName isEqualToString:@"com_dialog_bg_2.png"]){
        // 修改图片的尺寸
        newImage = [newImage imageWithNewScaledToSize:CGSizeMake(newImage.size.width * scale, newImage.size.height * scale )];
    }else {
        // 修改图片的尺寸
        newImage = [newImage imageWithNewScaledToSize:CGSizeMake(newImage.size.width * kImgScale * scale * fitScale, newImage.size.height * scale * kImgScale * fitScale)];
    }
    return newImage;
}

- (UIImage *)resizableImage {
    // 设置端盖的值
    CGFloat top = self.size.height * 0.5;
    CGFloat left = self.size.width * 0.5;
    CGFloat bottom = self.size.height * 0.5;
    CGFloat right = self.size.width * 0.5;
    
    // 设置端盖的值
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(top, left, bottom, right);
    // 设置拉伸的模式
    UIImageResizingMode mode = UIImageResizingModeTile;
    
    // 拉伸图片
    UIImage *newImage = [self resizableImageWithCapInsets:edgeInsets resizingMode:mode];
    return newImage;
}

- (UIImage *)resizableImageWithPoint:(CGPoint)point {
    
    // 设置端盖的值
    CGFloat top = self.size.height * (point.y);
    CGFloat left = self.size.width * (point.x);
    CGFloat bottom = self.size.height * (1 - point.y);
    CGFloat right = self.size.width * (1 - point.x);
    
    // 设置端盖的值
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(top, left, bottom, right);
    // 设置拉伸的模式
    UIImageResizingMode mode = UIImageResizingModeTile;
    
    // 拉伸图片
    UIImage *newImage = [self resizableImageWithCapInsets:edgeInsets resizingMode:mode];
    return newImage;
}


- ( UIImage *)imageWithNewScaledToSize:( CGSize )newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext (newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [self drawInRect : CGRectMake ( 0 , 0 ,newSize. width ,newSize. height )];
    // Get the new image from the context
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext ();
    // End the context
    UIGraphicsEndImageContext ();
    
    return newImage;
}

- (UIImage *)imageWithNewScaled:(CGFloat)scale {
    return [self imageWithNewScaledToSize:CGSizeMake(self.size.width  * scale * FITW, self.size.height * scale  * FITW)];
//    return [self imageByResizeToSize:CGSizeMake(self.size.width * scale, self.size.height * scale)];
}

//二、截图功能，实现用户想要截取图的RECT
- ( UIImage *)getImageInRect:( CGRect )rect{
    // 大图 bigImage
    // 定义 myImageRect ，截图的区域
    
    CGRect myImageRect = rect;
    UIImage * bigImage= self;
    CGImageRef imageRef = bigImage. CGImage ;
    
    CGImageRef subImageRef = CGImageCreateWithImageInRect (imageRef, myImageRect);
    
    CGSize size;
    size. width = rect. size . width ;
    size. height = rect. size . height ;
    
    UIGraphicsBeginImageContext (size);
    
    CGContextRef context = UIGraphicsGetCurrentContext ();
    CGContextDrawImage (context, myImageRect, subImageRef);
    UIImage * smallImage = [ UIImage imageWithCGImage :subImageRef];
    
    UIGraphicsEndImageContext ();
    
    return smallImage;
    
}

+ (UIImage *) combine:(UIImage*)image1 :(UIImage*)image2 {
    UIGraphicsBeginImageContext(CGSizeMake(image1.size.width+image2.size.width, image1.size.height));
    // Draw image1
    [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
    // Draw image2
    [image2 drawInRect:CGRectMake(image1.size.width, 0, image2.size.width, image2.size.height)];
    
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultingImage;
}

- (UIImage *) appendImg:(UIImage*)image{
    
    UIGraphicsBeginImageContext(self.size);
    // Draw image1
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    
    // Draw image2
//    image = [image transformImageSkewWithAngel:15];
    
    [image drawInRect:CGRectMake(self.size.width - image.size.width, 0, image.size.width, image.size.height)];
//     [image drawInRect:CGRectMake(10, 0, 10,10)];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultingImage;
}

- (UIImage *) appendGoldImg:(UIImage*)image offsetX:(CGFloat)offsetX{
    UIGraphicsBeginImageContext(self.size);
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    [image drawInRect:CGRectMake(self.size.width - image.size.width - offsetX*2 - 4, self.size.height/8, image.size.width, image.size.height)];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

//按照UIImageOrientation的定义，利用矩阵自定义实现对应的变换；
-(UIImage *)transformImageSkewWithAngel:(CGFloat)angle
{
    CGImageRef imgRef = self.CGImage;
    
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    CGRect bounds = CGRectMake(0, 0, width, height);
    CGFloat scaleRatio = 1;
    
//    CGFloat boundHeight;
    UIGraphicsBeginImageContext(bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    UIImageOrientation orient = self.imageOrientation;
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }
//    CGAffineTransform transform = CGAffineTransformMakeSkew(ANGEL(angle), 0);
    
    CATransform3D transform3d = CATransform3DMakeRotation(ANGEL(30), -1, 0, 0);
    CGAffineTransform transform1 = CATransform3DGetAffineTransform(transform3d);
    
    CGAffineTransform transform2 = CGAffineTransformMakeSkew(ANGEL(angle), 0);
    
    CGAffineTransform transform = CGAffineTransformConcat(transform1,transform2);
    
    CGContextConcatCTM(context, transform);
    
    CGContextDrawImage(UIGraphicsGetCurrentContext(), bounds, imgRef);
    
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return imageCopy;
}

- (UIImage *)changeImageByTransform:(CGAffineTransform)transform {
    CGImageRef imgRef = self.CGImage;
    CGFloat height = self.size.height;
    CGFloat width = self.size.width;
    CGRect bounds = CGRectMake(0, 0, width, height);
    CGFloat scaleRatio = 1;
    
    UIGraphicsBeginImageContext(self.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    // quartz 2d 使用的坐标系不同 转换坐标系
//    CGContextTranslateCTM(context, 0, height);
//    CGContextScaleCTM(context, 1, -1);
    UIImageOrientation orient = self.imageOrientation;
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }
    
    CGContextConcatCTM(context, transform);
    CGContextDrawImage(context,bounds, imgRef);
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImg;
}

- (UIImage *)imageXListWithAngel:(CGFloat)angel {
    CGAffineTransform transform = CGAffineTransformMake(1, 0, tan(angel), 1, 0, 0);
    return [self changeImageByTransform:transform];
}

- (UIImage *)imageYListWithAngel:(CGFloat)angel {
    CATransform3D transform3d = CATransform3DIdentity;
    transform3d.m34 = - 1.0 / 500.0;
    transform3d = CATransform3DRotate(transform3d, M_PI_4, 0, 1, 0);
    //apply to layer
//    CATransform3D transform3d = CATransform3DMakeRotation(angel, -1, 0, 0);
    CGAffineTransform transform = CATransform3DGetAffineTransform(transform3d);
    return [self changeImageByTransform:transform];
}

- (UIImage *)drawImageOnCenter:(UIImage *)image {
    UIGraphicsBeginImageContext(self.size);
    // Draw image1
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    
    [image drawInRect:CGRectMake(self.size.width/2 - image.size.width/2,self.size.height/2 - image.size.height/2, image.size.width, image.size.height)];

    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultingImage;
}

@end
